/*
 * Copyright (c) Tan Menglong.
 * All rights reserved.
 * 
 * This file is part of the RabbitOS.  The RabbitOS is free software, also known
 * as "open source;" you can redistribute it and/or modify it under the terms
 * of the GNU General Public License (GPL), version 2, as published by the Free
 * Software Foundation (FSF).  To explore alternate licensing terms, contact
 * the Tan Menglong at TanMenglong@gmail.com or +86-15972108715.
 * 
 * The RabbitOS is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GPL for more details.  You should have
 * received a copy of the GPL along with the RabbitOS; see the file COPYING.  If
 * not, write to the FSF, 59 Temple Place #330, Boston, MA 02111-1307, USA.
 */
/*
 * Timer.
 * 10-Jun-08
 */

#include <global.h>
#include <init/timer.h>
#include <init/isr.h>

volatile u32int tick = 0; // volatile is necessary - liuw

static void timer_callback(registers_t regs)
{
	tick++;
	//printk("Tick: ");
	//printk("%d\n", tick);
	return;
}

void init_timer(u32int frequency)
{
	// Firstly, register our timer callback.
	register_interrupt_handler(IRQ0, &timer_callback);

	// The value we send to the PIT is the value to divide it's input clock
	// (1193180 Hz) by, to get our required frequency. Important to note is
	// that the divisor must be small enough to fit into 16-bits.
	u32int divisor = 1193180 / frequency;

	// Send the command byte.
	outb(0x43, 0x36);

	// Divisor has to be sent byte-wise, so split here into upper/lower bytes.
	u8int l = (u8int) (divisor & 0xFF);
	u8int h = (u8int) ((divisor >> 8) & 0xFF);

	// Send the frequency divisor.
	outb(0x40, l);
	outb(0x40, h);

	// set mask - liuw
	outb(0x21, 0xfe);
}
